document.addEventListener('DOMContentLoaded', function() {
    // 初始化视频播放器
    const player = videojs('my-video', {
        fluid: true,
        responsive: true,
        playbackRates: [0.5, 1, 1.5, 2],
        controlBar: {
            children: [
                'playToggle',
                'volumePanel',
                'progressControl',
                'currentTimeDisplay',
                'timeDivider',
                'durationDisplay',
                'playbackRateMenuButton',
                'fullscreenToggle'
            ]
        }
    });

    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const videoUrl = urlParams.get('url');
    const videoTitle = urlParams.get('title') || '视频播放';

    // 设置视频源和标题
    if (videoUrl) {
        document.getElementById('video-source').src = videoUrl;
        document.getElementById('video-title').textContent = videoTitle;
        player.load(); // 重新加载视频
    }

    // 显示加载状态
    const loadingOverlay = document.getElementById('loading');
    player.on('loadstart', () => {
        loadingOverlay.style.display = 'flex';
    });

    player.on('canplay', () => {
        loadingOverlay.style.display = 'none';
    });

    player.on('error', () => {
        loadingOverlay.style.display = 'none';
        alert('视频加载失败，请检查视频地址是否正确');
    });

    // 下载按钮点击事件
    document.getElementById('download-btn').addEventListener('click', async () => {
        if (!videoUrl) {
            alert('视频地址不存在');
            return;
        }

        try {
            loadingOverlay.style.display = 'flex';
            loadingOverlay.querySelector('p').textContent = '正在准备下载...';

            const response = await fetch(videoUrl);
            if (!response.ok) throw new Error('下载失败');

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = videoTitle + '.mp4';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error('下载视频失败:', error);
            alert('下载视频失败: ' + error.message);
        } finally {
            loadingOverlay.style.display = 'none';
            loadingOverlay.querySelector('p').textContent = '视频加载中...';
        }
    });
}); 